package com.ivy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ivy.dao.SchoolDao;
import com.ivy.dao.impl.SchoolDaoImpl;
import com.ivy.entity.School;
import com.ivy.utils.DataReadUtils;

public class SchoolServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public SchoolServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	private SchoolDao sdao = new SchoolDaoImpl();
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		//School school = DataReadUtils.copyBean(request, School.class);
		
		List<School> schools = sdao.findAllSchool();
//		School school = sdao.findSchoolById(1);
//		System.out.println("------------"+school.getCookiepath());
		JSONArray arr = new JSONArray();
		for(int i=0;i<schools.size();i++) {
			School s = schools.get(i);
			JSONObject obj = new JSONObject();
			
			try {
				obj.put("id", s.getId());
				obj.put("sname", s.getSname());
				obj.put("listpath", s.getListpath());
				obj.put("listcookie", s.getListcookie());
				obj.put("referer", s.getReferer());
				obj.put("cookiepath", s.getCookiepath());
				obj.put("coursepath", s.getCoursepath());
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
			arr.put(obj);
			
		}
		
		response.getWriter().print(arr);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
